/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.io.File;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Audio;
import android.widget.Toast;

import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.ReturnItem;
import com.phonebooksharing.dto.msg.VoiceMessageItem;

public class SendVoiceMessageTask extends NetworkHandlerTask<String, Void, Boolean> {
    private ProgressDialog progress;
    private Context cx;
    protected VoiceMessageItem voiceMsg;
    private Uri recordedUri;
    private ArrayList<Integer> groupList;
    private long dashboardID;
    
    public SendVoiceMessageTask(Context cx, ArrayList<Integer> groupList, String recordedUri) {
        this(cx, -1, groupList, recordedUri);
    }
    
    public SendVoiceMessageTask(Context cx, long dashboardID, ArrayList<Integer> groupList, String recordedUri) {
        this.cx = cx;
        this.recordedUri = Uri.parse(recordedUri);
        this.groupList = groupList;
        this.dashboardID = dashboardID;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        
        progress = new ProgressDialog(cx);
        progress.setTitle("Processing");
        progress.setMessage("Please wait while we post your message...");
        progress.setIndeterminate(true);
        progress.setCancelable(false);
        progress.show();
    }

    @Override
    protected Boolean doInBackground(String... texts) {
        
        boolean isOK = false;
        voiceMsg = new VoiceMessageItem();
        try {
            ContentResolver cr = cx.getContentResolver();
            voiceMsg.title = texts[0];//title
            voiceMsg.when  = GeneralUtils.getGmtTimeInMilis();
            
            Cursor c = null;
            String audioPath = "";
            try {
                c = cr.query(recordedUri, new String[] {Audio.Media.DURATION, Audio.Media.MIME_TYPE, Audio.Media.DATA}, null, null, null);
                if(c != null && c.moveToFirst()) {
                    voiceMsg.length = GeneralUtils.getLengthByMilis(c.getLong(0));
                    voiceMsg.mimeType = c.getString(1);
                    audioPath = c.getString(2);
                }
            } finally {
                CloseableUtil.safeClose(c);
                c = null;
            }
            
            GenericTransferDTO g = new GenericTransferDTO();
            g.authItem   = Global.authItem;
            g.simpleItem = voiceMsg;
            g.simpleID   = dashboardID;
            
            String url = String.format(Global.MESSAGE_SERVLET_URL, "cv" /*ac*/, "c" /*t*/, "" /*q*/, "" /*mt*/);
            VoiceMessageItem vi = (VoiceMessageItem)doNetworkPost(url, g);
            
            url = String.format("http:" + Global.MESSAGE_SERVLET_URL, "cv" /*ac*/, "u" /*t*/, vi.voiceMessageID /*q*/, vi.mimeType /*mt*/);
            
            GalleryUtilities.uploadBinaryStream(url, new File(audioPath));
            IOUtilities.add2collection(audioPath);
            cr.delete(recordedUri, null, null);
            
            url = String.format(Global.MESSAGE_SERVLET_URL, "cv" /*ac*/, "d" /*t*/, (dashboardID > 0 ? "i" : "g") /*q*/, "" /*mt*/);
            g.simpleItem = vi;
            g.items2     = groupList;
            ReturnItem ri = (ReturnItem)doNetworkPost(url, g);
            
            isOK = ri.isOK();
        } catch (Exception e) {
            e.printStackTrace();
            isOK = false;
        }
//        if(!isOK) {
//            PhonebookSharingManager.addMsgSync(cx,
//                  voiceMsg.title,
//                  voiceMsg.text,
//                  Message.MSG_TYPE_TEXT);
//        }
//        
        return isOK;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        progress.dismiss();
        if(result) {
            Toast.makeText(cx, "Your message has been send successfully!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(cx, "It was not possible to deliver your message.\n\nPlease try it again...", Toast.LENGTH_LONG).show();
        }
    }
}